package net.code4life.core.webserver;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServerWapper{

	private static Log logger = LogFactory.getLog(JettyServerWapper.class);
	
	private Server server;
	private int port;
	private String cxtpath;
	private String rootDir="ROOT";
	
	public JettyServerWapper(int port, String cxtpath, String rootDir) {
		this(port, cxtpath);
		this.rootDir = rootDir;
	}
	public JettyServerWapper(int port, String cxtpath) {
		this.port = port;
		this.cxtpath = cxtpath;
		initServer();
	}
	
	private void initServer(){
		File webappsDir = new File(cxtpath);
		server = new Server();
		Connector connector = new SelectChannelConnector();
		connector.setPort(this.port);
		server.addConnector(connector);
		
		//Webapps init
		HandlerCollection handlers = new HandlerCollection();
		if(webappsDir.exists()){
			for(File file : webappsDir.listFiles()){
				if(file.isDirectory()){
					if(this.rootDir.equalsIgnoreCase(file.getName())){
						addContext(handlers, file, "/");
					} else {
						addContext(handlers, file, "/"+file.getName());
					}
				}
			}
		}
		
		this.server.setHandler(handlers);
		this.server.setStopAtShutdown(true);
	}
	
	private void addContext(HandlerCollection handlers, File dir,String contenxtPath){
		if(logger.isInfoEnabled()){
			logger.info("add WebAppContext "+contenxtPath+"----->"+dir.getAbsolutePath());
		}
		WebAppContext wac = new WebAppContext();
		wac.setWar(dir.getAbsolutePath());
		wac.setContextPath(contenxtPath);
		handlers.addHandler(wac);
	}
	
	public void start() throws Exception{
		this.server.start();
	}
	public void stop() throws Exception {
		this.server.stop();
	}
}
